<template>
  <div>
    <UploadExcel :before-upload="beforeUpload" :on-success="handleUpload" />
  </div>
</template>

<script>
import { batchAddEmp } from '@/api/employees'
import { formatDate } from '@/filters/filters'
export default {
  name: 'ImportExcel',
  methods: {
    beforeUpload(file) {
      if (/\.(xlsx|xls)$/.test(file.name)) {
        return true
      }
      this.$message.errog('请选择xlsx或xls格式的文件')
      return false
    },
    async handleUpload({ results, header }) {
      console.log(results)
      const userRelations = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        聘用形式: 'formOfEmployment'
      }
      const newList = results.map((value) => {
        const temp = {}
        for (const key in value) {
          const enKey = userRelations[key]
          if (key == '入职时间' || key == '转正日期') {
            const excelTime = value[key]
            const date = new Date((excelTime - 1) * 24 * 60 * 60 * 1000)
            const year = date.getFullYear()
            date.setFullYear(year - 70)
            temp[enKey] = formatDate(date)
          } else {
            temp[enKey] = value[key]
          }
        }
        return temp
      })
      if (this.$route.query.type == 'employees') {
        await batchAddEmp(newList)
      }
    }
  }
}
</script>

<style></style>
